"""
Case Type   : 服务端工具
Case Name   : 单节点/集群使用gs_check -i CheckTimeZone不指定-L 参数
Create At   : 2024-10-9
Owner       : ningyali
Description :
    1.集群减容，只至只剩单节点
    2.执行命令gs_check -i CheckTimeZone
    3.执行命令gs_check -i CheckTimeZone -L
    4.扩容./gs_expansion -U test -G test -X xml_path -h 扩容节点host -L
    5.执行命令gs_check -i CheckTimeZone
    6.执行命令gs_check -i CheckTimeZone -L
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.执行成功
    5.执行成功，回显与第3步一致
    6.执行成功，回显与第4步一致
History     : 
"""
import os
import re
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)
        self.constant = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.node_num = self.pri_sh.get_node_num()
        self.script_path = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'tool', 'script')
        self.cluster = {'pri_root': Node('PrimaryRoot'),
                        'pri_user': Node('PrimaryDbUser')}
        self.user = self.cluster["pri_user"].ssh_user
        self.pri_host = self.cluster["pri_user"].ssh_host
        if self.node_num == 3:
            self.cluster['sta1_user'] = Node('Standby1DbUser')
            self.cluster['sta2_user'] = Node('Standby2DbUser')
            self.sta1_host = self.cluster["sta1_user"].ssh_host
            self.sta2_host = self.cluster["sta2_user"].ssh_host
            self.dropnode_cmd = f'source {macro.DB_ENV_PATH};' \
                                f'yes|gs_dropnode -U {self.user} ' \
                                f'-G {self.user} ' \
                                f'-h {self.sta1_host},{self.sta2_host}'
            self.expansion_cmd = f'cd {self.script_path};' \
                                 f'source {macro.DB_ENV_PATH};' \
                                 f'./gs_expansion -U {self.user} ' \
                                 f'-G {self.user} -X {macro.DB_XML_PATH} ' \
                                 f'-h {self.sta1_host},{self.sta2_host} -L'

    def test_server_tools(self):
        text = '----step1: 集群减容，只至只剩单节点 expect: 执行成功----'
        self.log.info(text)
        if self.node_num == 3:
            self.log.info(self.dropnode_cmd)
            res = self.cluster["pri_user"].sh(self.dropnode_cmd).result()
            self.log.info(res)
            expect = '[gs_dropnode]Success to drop the target nodes'
            self.assertIn(expect, res, f'执行失败:{text}')

        text = '----step2: 执行命令gs_check -i CheckTimeZone expect: 执行成功----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_check -i CheckTimeZone'
        self.log.info(cmd)
        res = self.cluster["pri_user"].sh(cmd).result()
        self.log.info(res)
        expect = 'The item run on 1 nodes.  success: 1  (consistent)'
        self.assertIn(expect, res, f'执行失败:{text}')

        text = '----step3: 执行命令gs_check -i CheckTimeZone -L expect: 执行成功----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_check -i CheckTimeZone -L'
        self.log.info(cmd)
        res = self.cluster["pri_user"].sh(cmd).result()
        self.log.info(res)
        expect = '[RST] OK'
        self.assertIn(expect, res, f'执行失败:{text}')

        text = '----step4: 扩容 expect: 执行成功----'
        self.log.info(text)
        if self.node_num == 3:
            self.log.info(self.expansion_cmd)
            res = self.cluster["pri_user"].sh(self.expansion_cmd).result()
            self.log.info(res)
            expect = f'Expansion Finish'
            expect1 = f'{self.sta1_host}:\tSuccess'
            expect2 = f'{self.sta2_host}:\tSuccess'
            self.assertIn(expect, res, f'执行失败:{text}')
            self.assertIn(expect1, res, f'执行失败:{text}')
            self.assertIn(expect2, res, f'执行失败:{text}')

        text = '----step5: 执行命令gs_check -i CheckTimeZone ' \
               'expect: 执行成功，回显与第3步一致----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_check -i CheckTimeZone'
        self.log.info(cmd)
        res = self.cluster["pri_user"].sh(cmd).result()
        self.log.info(res)
        expect = f'The item run on {self.node_num} nodes.  ' \
                 f'success: {self.node_num}  (consistent)'
        self.assertIn(expect, res, f'执行失败:{text}')

        text = '----step6: 执行命令gs_check -i CheckTimeZone -L ' \
               'expect: 执行成功，回显与第3步一致----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_check -i CheckTimeZone -L'
        self.log.info(cmd)
        res = self.cluster["pri_user"].sh(cmd).result()
        self.log.info(res)
        expect = '[RST] OK'
        self.assertIn(expect, res, f'执行失败:{text}')

    def tearDown(self):
        text = f'----检查集群状态是否正常----'
        self.log.info(text)
        db_status = self.pri_sh.get_db_cluster_status('all')
        self.log.info(db_status)
        regex_res = re.findall('(instance_state.*:.*Normal)', db_status)
        self.log.info(regex_res)

        if len(regex_res) != self.node_num:
            text = '----建立root互信，执行扩容----'
            self.log.info(text)
            self.log.info(self.expansion_cmd)
            if self.sta1_host in db_status and\
                    self.sta2_host not in db_status:
                expansion_cmd = self.expansion_cmd.replace(
                    f'{self.sta1_host},', '')
            elif self.sta1_host not in db_status and \
                    self.sta2_host in db_status:
                expansion_cmd = self.expansion_cmd.replace(
                    f',{self.sta2_host}', '')
            else:
                expansion_cmd = self.expansion_cmd
            res = self.cluster["pri_root"].sh(expansion_cmd).result()
            self.log.info(res)
            expect = 'Expansion results:.*:.*Success.*Expansion Finish.'
            regex_res = re.search(expect, res, re.S)
            self.log.info(regex_res)
            self.assertIsNotNone(regex_res, f'执行失败: {text}')
        text = f'-----{os.path.basename(__file__)} end-----'
        self.log.info(text)
